import './Workflow.scss';
import * as React from 'react';
import { connect } from 'react-redux';
import WorkflowOperaItem from './WorkflowOperaItem';
import WorkflowNode from './WorkflowNode';

import { changeOperaType, createNode } from '../../reducer/controller';
import { OperaType, NodeArray } from '../../reducer/const';

import { ICreateNodeData } from '../../reducer/const';


interface IProps {
    /** 操作模式 */
    operaType: number;
    /** 新增节点类型 */
    nodeType: number;
    /** 改变操作模式 */
    changeOperaType: (operaType: number) => any;
    /** 新增节点 */
    createNode: (createNodeData: ICreateNodeData) => any;
}

class WorkflowToolBar extends React.Component<IProps, any> {

    constructor(props: IProps) {
        super(props);
        this.state = {
            operaType: this.props.operaType
        };
    }

    componentWillReceiveProps(nextProps: IProps, nextContext: any) {
        const newOperaType = nextProps.operaType;
        const {operaType} = this.state;
        if (newOperaType !== operaType) {
            this.setState({
                operaType: newOperaType
            });
        }
    }

    clickOpera = (type) => {
        const {operaType} = this.state;
        if (operaType !== type) {
            this.props.changeOperaType(type);
        }
    }

    createNode = (createNodeData: ICreateNodeData) => {
        this.props.createNode(createNodeData);
    }

    dragModel = () => {
        return this.props.operaType === OperaType.Drag;
    }

    lineModel = () => {
        return this.props.operaType === OperaType.Linked;
    }

    render() {
        return (
            <div className='workflow__toolbar noselect'>
                <div className='workflow__theader'>
                    工具栏
                </div>
                <div className='workflow__tbody noselect' >
                    <WorkflowOperaItem tooltip='绘制节点' icon='icon-drag' onclick={this.clickOpera} type={OperaType.Drag} active={this.dragModel()} />
                    <WorkflowOperaItem tooltip='链接节点' icon='icon-line' onclick={this.clickOpera} type={OperaType.Linked} active={this.lineModel()} />
                    <div className='workflow__line'></div>
                    {
                        NodeArray.map(item => (<WorkflowNode {...item} onDrag={this.createNode} disabled={this.lineModel()} />))
                    }
                </div>
            </div>
        );
    }
};


const mapStateToProps = (state: any) => {
    const { operaType, nodeType } = state.action;
    return {
        operaType,
        nodeType
    };
};

const mapDispatchToProps = (dispatch: any) => ({
    changeOperaType: (operaType: number) => dispatch(changeOperaType(operaType)),
    createNode: (createNodeData: ICreateNodeData) => dispatch(createNode(createNodeData)),
});

export default connect(mapStateToProps, mapDispatchToProps)(WorkflowToolBar);
